package cn.wolfcode.web.interceptor;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Permission;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.util.RequiredPermission;
import cn.wolfcode.util.UserContextUtil;
import com.alibaba.fastjson.JSON;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class CheckPermissionInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        //判断是否是后台请求
        if(handler instanceof HandlerMethod){
            Employee employee = UserContextUtil.getCurrentEmployee();
            //判断是否是超级管理员
            if (!employee.isAdmin()){
                HandlerMethod handlerMethod = (HandlerMethod) handler;
                RequiredPermission requiredPermission = handlerMethod.getMethodAnnotation(RequiredPermission.class);
                //判断请求的目标方法上是否贴权限注解
                if(requiredPermission != null){
                    //获取方法上的权限表达式和用户的权限集合
                    String expression = requiredPermission.expression();
                    List<Permission> permissionList = UserContextUtil.getCurrentPermissions();
                    for (Permission permission : permissionList) {
                        //判断用户权限集合的的权限是否有与方法上的匹配
                        if(permission.getExpression().equals(expression)){
                           return true;
                        }
                    }
                    //判断请求类型
                    ResponseBody responseBody = handlerMethod.getMethodAnnotation(ResponseBody.class);
                    if(responseBody == null){
                        response.sendRedirect("/noPermission");
                    }else{
                        //ajax方式访问返回自定义json对象
                        JsonResult jsonResult = new JsonResult();
                        jsonResult.setSuccess(false);
                        jsonResult.setMsg("您没有该操作权限,请联系管理员!");
                        response.setContentType("application/json;charset=utf-8");
                        response.getWriter().write(JSON.toJSONString(jsonResult));
                        return false;
                    }
                }
            }
        }
        return true;
    }
}
